package edu.buaa.resourceManager.server;

import java.util.concurrent.PriorityBlockingQueue;

/**
 * Created by sjh on 17-7-2.
 */
public class BackgroundTaskExecutor extends Thread
{
    private static PriorityBlockingQueue<BackgroundTask> queue = new PriorityBlockingQueue<>(1000);

    public static void init(int parallelCount)
    {
        for(int i=0; i<parallelCount; i++){
            new BackgroundTaskExecutor().start();
        }
    }

    public static void addTask(BackgroundTask task){
        queue.add(task);
    }

    public static void exit(){
        queue.add(new Exit());
    }

    private static class Exit extends BackgroundTask{
        Exit(){
            this.setExit(true);
        }
        @Override
        public void run() {}
    }

    private BackgroundTaskExecutor(){

    }

    @Override
    public void run()
    {
        while(true)
        {
            BackgroundTask task = queue.poll();
            if(task.getExit()){
                queue.add(task);
                break;
            }else {
                task.run();
            }
        }
    }
}
